<!--
@description    绩效报表-我的绩效
@author         秦俊强
@email          458112865@qq.com
@create         2020-02-17 18:15
-->

<template>
  <div class="ant-card ant-card-body">

    <!-- 菜单区 start -->
    <div class="menu-box">
      <div class="query-date">
        <span>考核期：</span>
        <a-select v-if="!yearList.loading"
                  :value="yearList.val.text"
                  @change="changeYear">
          <a-select-option v-for="date in yearList.arr"
                           :key="date.value">{{ date.text }}</a-select-option>
        </a-select>

        <a-select v-else :defaultValue="'数据加载中'" disabled></a-select>
      </div>
    </div>
    <!-- 菜单区 end -->


    <!-- 内容区 start -->
    <div class="content-box">
      <!-- 1. 概览信息 start -->
      <div class="table-view">
        <div class="title">
          <span>概览</span>

          <!-- 视图切换 start -->
          <div class="view-switch-box">
            <!-- 切换成图表 -->
            <div class="view-chart"
                 :class="getCheckedClass('chart')"
                 @click="checkedView('chart')">
              <a-icon type="bar-chart" title="显示图表" />
            </div>

            <!-- 切换成表格 -->
            <div class="view-table"
                 :class="getCheckedClass('table')"
                 @click="checkedView('table')">
              <a-icon type="table" title="显示表格" />
            </div>
          </div>
          <!-- 视图切换 end -->
        </div>

        <div class="view-box">
          <!-- 表格视图 -->
          <a-table v-if="viewType === 'table'"
                   :loading="tableViewData.loading"
                   :scroll="tableViewData.scroll"
                   :columns="tableViewData.columns"
                   :dataSource="tableViewData.dataSource"

                   :pagination="false" bordered>
            <template :slot="'operation'" slot-scope="text, record,ind">
              <span class="score-ref" @click="click(record,ind,'p')">总经理评分</span>
              <span style="margin: 3px">|</span>
              <span class="score-ref" @click="click1(record,ind,'t')">调整记录</span>
            </template>

          </a-table>
          <!--:customRow="click"-->
          <!-- 图表视图 -->
          <ChartScoreView v-else :year="yearList.val" ref="chartView"
                          :chartData="tableViewData"></ChartScoreView>
        </div>
      </div>
      <!-- 1. 概览信息 end -->

      <!-- 2. 详细信息 start -->
      <div class="table-detail">
        <div class="title">
          <span>详情</span>

          <!-- 导出我的报表 -->
          <div class="view-switch-box">
            <a-button icon="upload" :loading="loadingExport1" style="margin-right: 10px;"
                      :disabled="this.size === 0"
                      @click="exportDetail(true)">
              <span>导出我的绩效报表(简报)</span>
            </a-button>

            <a-button icon="upload" :loading="loadingExport2"
                      :disabled="this.size === 0"
                      @click="exportDetail()">
              <span>导出我的绩效报表(全部)</span>
            </a-button>
          </div>
        </div>

        <div class="radio-box">
          <div class="radio-org">
            <span>部门：</span>
            <span>
              <a-radio-group v-if="tableViewData.loading" buttonStyle="solid"
                             :value="'数据加载中...'" disabled>
                <a-radio-button>数据加载中...</a-radio-button>
              </a-radio-group>

              <a-radio-group v-else-if="tableViewData.dataSource.length > 0"
                             buttonStyle="solid" :value="orgVal.radio_id"
                             :disabled="tableDetailData.loading" @change="changeOrg">
                <a-radio-button v-for="org in tableViewData.dataSource"
                                :value="org.radio_id">
                  <span>{{ org.indexOrgName }}</span>
                  <span>({{ org.scorerName }})</span>
                </a-radio-button>
              </a-radio-group>

              <a-radio-group v-else buttonStyle="solid"
                             :value="'暂无部门信息'" disabled>
                <a-radio-button>暂无部门信息</a-radio-button>
              </a-radio-group>

              <a-checkbox @change="onChangeIsTotal" :checked="isTotal">只看简报</a-checkbox>
            </span>
          </div>

          <div class="radio-month">
            <span>月份：</span>
            <span>
              <a-radio-group :disabled="isDisabled()" buttonStyle="solid"
                             :value="monthList.val.value" @change="changeMonth">
              <a-radio-button v-for="month in monthList.arr" :value="month.value">
                <span>{{ month.text }}</span>
              </a-radio-button>
            </a-radio-group>
            </span>
          </div>
        </div>

        <div class="view-box">
          <a-table :loading="tableDetailData.loading"
                   :scroll="tableDetailData.scroll"
                   :columns="tableDetailData.columns"
                   :dataSource="tableDetailData.dataSource"
                   :pagination="false" bordered
                   :locale="{ emptyText: getEmptyText() }"
                   :rowClassName="isLine">

            <!--指标展示-->
            <template :slot="'indexName'"
                      slot-scope="text, record, ind">
                <span style="white-space: pre-wrap">{{ text }} </span>
            </template>

            <!-- 数据项展示 start -->
            <template :slot="'indexValueName'"
                      slot-scope="text, record, ind">
              <div>
                <span>{{ text }} </span>

                <!-- 图表 icon -->
                <a-icon class="icon-chart" type="bar-chart"
                        v-if="record.showChart"
                        @click="showChartPop(record)" />
                <a-icon class="icon-chart" type="code"
                        v-if="record.showLine && record.indexValueAttr != '60'"
                        @click="showScore(record)" />
              </div>
            </template>
            <!-- 数据项展示 end -->

          </a-table>
        </div>

        <!-- 分页器 start -->
        <div class="pagination-box">
          <a-pagination :current="pageData.pageNo"
                        :pageSize="pageData.pageSize"
                        :total="pageData.total"
                        :pageSizeOptions="[ '20', '30', '40']"
                        @change="changePage"
                        showSizeChanger
                        @showSizeChange="onShowSizeChange"  />
        </div>
        <!-- 分页器 end -->
      </div>
      <!-- 2. 详细信息 end -->
    </div>
    <!-- 内容区 end -->


    <!-- 弹窗 达成率 start -->
    <a-modal v-model="modalInfo.show"
             :title="modalInfo.title"
             :footer="null" :width="'90%'">
      <ChartCompletionRate :yearMonth="modalInfo.yearMonth"
                           :data="modalInfo.data"
                           ref="chartCompletionRate"></ChartCompletionRate>
    </a-modal>
    <!-- 弹窗 达成率 end -->

    <!-- 弹窗 得分 start -->
    <a-modal v-model="scoreInfo.show"
             :title="scoreInfo.title"
             :footer="null" :width="'90%'"
             :destroyOnClose="true"
    >
      <Score :yearMonth="scoreInfo.yearMonth"
             :data="scoreInfo.data"
            ></Score>
    </a-modal>
    <!-- 弹窗 得分 end -->

    <!-- 弹窗 月份评价详细 start -->
    <a-modal v-model="modalInfo1.show"
             :title="modalInfo1.title"
             :width="'60%'"
             :destroyOnClose="true"
             :footer="null">
      <ScoreModel ref="scoreRef"
                      :departInfo="modalInfo1.departInfo"
                      :date="modalInfo1.date"
                      :k="modalInfo1.k"
                      :param="modalInfo1.param"

      ></ScoreModel>
    </a-modal>
    <!--  end -->
  </div>
</template>



<script>

  /* 引入表格配置 */
  import { tableViewData, tableDetailData, getMonthData } from './configs/table.myReport.config';

  /* 封装通用 api 服务 */
  import { apiService } from '@/api/api.service.js';
  import { deleteAction, getAction,downFile,httpAction } from '@/api/manage'
  /* 评价详情弹窗 */
  import ScoreModel from '../components/scoreCommon/ScoreModel';

  /**
   * api 接口
   *
   * getCheckYearList => 获取 年份列表
   * getGradeViewDatagrid => 获取 概览信息
   * getGradeDetailDatagrid => 获取 详情列表
   * exportXlsx => 导出我的绩效详情
   * */
  import { getCheckYearList, getGradeViewDatagrid, getGradeDetailDatagrid, exportXlsx } from '@/api/api.js';

  /* 引入图表概览组件 */
  import ChartScoreView from './components/ChartScoreView';

  /* 引入达成率组件 */
  import ChartCompletionRate from './components/ChartCompletionRate';
  /* 引入得分组件 */
  import Score from './components/Score';






  export default {
    components: { ChartScoreView, ChartCompletionRate,Score ,ScoreModel},

    data() {
      return {
        /* 年下拉菜单 */
        yearList: {
          loading: false,
          arr: [],    // 可选择的年份列表
          val: {}     // 已选年，默认数组第 0 个
        },

        /* 分页 */
        pageData: {
          pageNo: 1,
          pageSize: 20,
          total: 1
        },

        /* 当前选中的部门 */
        orgVal: {},

        /* 详情需要选择的月份 */
        monthList: {
          arr: getMonthData(),
          val: {}
        },

        /* table 表格 | chart 图表 */
        viewType: 'table',

        /* 概览表格 */
        tableViewData: tableViewData(),

        /* 详情表格 */
        tableDetailData: {},

        /* 达成率弹窗 */
        modalInfo: {
          show: false,
          title: '',
          yearMonth: {},
          data: {}
        },
   /* 月份点击查看评价详情弹窗信息 */
        modalInfo1: {
          show: false,
          title: '',
          date: '',
          departInfo: {},
          k:'',
          param:'',
        },
        /* 得分弹窗 */
        scoreInfo: {
          show: false,
          title: '',
          yearMonth: {},
          data: {}
        },

        /* 是否导出中 1 简报 | 2 全部 */
        loadingExport1: false,
        loadingExport2: false,

        /* 是否只看简报 */
        isTotal: true,

        /* 是否导出报表 */
        size: 0,
      }
    },

    created() {
      let _this = this;
      this.yearList.loading = true;
      apiService(getCheckYearList()).then((res) => {
        let list = res.result || [];
        this.yearList = {
          loading: false,
          arr: list,
          val: list[0]
        };

        this.getGradeViewData();
      }).catch((error) => {
        this.yearList.loading = false;
        this.$message.error(error.message);
      });
    },

    methods: {

      /* 返回当前概览显示的类型是表格还是图表样式 */
      getCheckedClass(str) {
        return (this.viewType === str) ? 'checked-on' : '';
      },

      /* 返回表格内容提示文字 */
      getEmptyText() {
        let month = this.monthList.val;   // 考核期 月
        if (!month.value) { return '请选择月份查看详情'; }
        return '';
      },

      /* 切换视图 */
      checkedView(str) {
        this.viewType = str;
      },

      /* 是否禁用选择月份 */
      isDisabled() {
        let tableViewData = this.tableViewData;
        let tableDetailData = this.tableDetailData;
        if (tableViewData.loading || tableDetailData.loading) { return true; }
        return (tableViewData.dataSource.length === 0);
      },

      /* 如果是分数行就高亮 */
      isLine(row) {
        if (row.showLine) {
          if (row.indexValueAttr == '40') { return 'row-line-auto'; }
          if (row.indexValueAttr == '50') { return 'row-line-more'; }
          if (row.indexValueAttr == '60') { return 'row-line-deep'; }
        }
        return '';
      },

      /* 查看图表 */
      showChartPop(record) {
        this.modalInfo.title = record.indexValueName;
        this.modalInfo.data = {
          view: this.orgVal,
          detail: record
        };

        let year = this.yearList.val;
        let month = this.monthList.val;
        this.modalInfo.yearMonth = {
          text: year.text + month.text,
          value: year.value + month.value
        };

        this.modalInfo.show = true;

        setTimeout(() => {
          /* 通知组件更新数据 */
          this.$refs.chartCompletionRate.getGradeChart();
        }, 100);
      },


      /* 查看得分弹窗 */
      showScore(record) {
        this.scoreInfo.title = record.indexName;
        this.scoreInfo.data = {
          view: this.orgVal,
          detail: record
        };
        let year = this.yearList.val;
        let month = this.monthList.val;
        this.scoreInfo.yearMonth = {
          text: year.text + month.text,
          value: year.value + month.value
        };

        this.scoreInfo.show = true;

      },

      /* 监听年份的变化 */
      changeYear(code) {
        let arr = this.yearList.arr;
        this.yearList.val = arr.find((item) => { return (item.value === code); });

        this.orgVal = {};
        this.monthList.val = {};
        this.tableDetailData.dataSource = [];

        this.changeColumns();
        this.getGradeViewData();
      },

      /* 监听部门选择的变化 */
      changeOrg(e) {
        let val = e.target.value;
        let arr = this.tableViewData.dataSource;
        this.orgVal = arr.find((item) => { return (item.radio_id === val); });

        this.getGradeDetailData();
      },

      /* 监听月份的变化 */
      changeMonth(e) {
        let val = e.target.value;
        let arr = this.monthList.arr;
        this.monthList.val = arr.find((item) => { return (item.value === val); });
        this.tableDetailData = tableDetailData(val);
        this.changeColumns();
        this.getGradeDetailData();
      },

      // 详情表格的动态列文字
      changeColumns() {
        this.pageData.total = 0;
        let val = this.monthList.val.value;
debugger;
        this.tableDetailData.columns.forEach((item) => {
          if (item.dataIndex === 'mTotal') {
            if (!val) {
              item.title = '1~N月汇总';
            } else if (parseInt(val) === 1) {
              item.title = '1月汇总';
            } else {
              item.title = '1~' + parseInt(val) + '月汇总';
            }
          }
        });
      },

      /* 监听页码改变 */
      changePage(pageNo) {
        this.pageData.pageNo = pageNo;
        this.getGradeDetailData();
      },

      /* 监听分页条数的改变 */
      onShowSizeChange(current, pageSize) {
        this.pageData.pageSize = pageSize;

        if (this.tableDetailData.dataSource.length > 0) {
          this.pageData.pageNo = 1;
          this.getGradeDetailData();
        }
      },

      /* 监听是否只看简报项的变化 */
      onChangeIsTotal(e) {
        this.isTotal = e.target.checked;
        this.pageData.pageNo = 1;
        this.getGradeDetailData();
      },

      /* 获取【详情】列表 */
      getGradeDetailData() {
        let orgVal = this.orgVal;         // 当前选中的部门
        let year = this.yearList.val;     // 考核期 年
        let month = this.monthList.val;   // 考核期 月
        let pageData = this.pageData;     // 分页

        if (!orgVal.indexOrgCode || !orgVal.scorerCode || !month.value) { return; }

        let param = {
          indexYearMonth: year.value + '' + month.value,
          indexDepart: orgVal.indexOrgCode,         // 得分部门
          scorerCode: orgVal.scorerCode,            // 得分部门负责人
          pageNo: pageData.pageNo,
          pageSize: pageData.pageSize,
          isTotal: this.isTotal,                    // 是否只看简报项
        }

        this.tableDetailData.loading = true;
        apiService(getGradeDetailDatagrid(param)).then((res) => {
          this.tableDetailData.loading = false;

          if (!res.success) {
            this.tableDetailData.dataSource = [];
            this.$message.warning(res.message);
            return;
          }

          let result = res.result;
          this.tableDetailData.dataSource = result.records || [];
          this.pageData.total = result.total;
          this.size=this.tableDetailData.dataSource.length;  //是否导出报表
        }).catch((error) => {
          this.tableDetailData.loading = false;
          this.tableDetailData.dataSource = [];
          this.$message.error(error.message);
        });
      },

      /* 获取【概览】信息 */
      getGradeViewData() {
        let _this = this;
        let param = {
          indexYear: this.yearList.val.value
        }

        this.tableViewData.loading = true;
        apiService(getGradeViewDatagrid(param)).then((res) => {
          this.tableViewData.loading = false;

          if (!res.success) {
            this.tableViewData.dataSource = [];
            this.$message.warning(res.message);
            return;
          }

          let result = res.result;
          this.tableViewData.dataSource = result.records || [];
          this.tableViewData.dataSource.forEach((item) => {
            item['radio_id'] = item.indexOrgCode + item.scorerCode;
          });

          /* 绩效详情默认高亮第 1 个部门 */
          _this.orgVal = _this.tableViewData.dataSource[0];

          /* 更新表格数据 */
          if (this.viewType === 'chart') {
            this.$refs.chartView.initChart();
          }
//默认选中最后有数据的月份
          let val = _this.orgVal.lastAuditYearMonth.slice(4);
          let arr = this.monthList.arr;
          this.monthList.val = arr.find((item) => { return (item.value === val); });
          debugger;
          this.tableDetailData =  tableDetailData(val);
          this.changeColumns();
          this.getGradeDetailData();



        }).catch((error) => {
          this.tableViewData.loading = false;
          this.tableViewData.dataSource = [];
          this.$message.error(error.message);
        });
      },

      /* 导出详情报表 */
      exportDetail(b) {
        let year = this.yearList.val;
        let month = this.monthList.val;
        let param = {
          "indexYearMonth": year.value + '' + month.value,
          "isTotal": b || false,                    // 下载简报 true | 下载全部 false
          "reportCode": "RIS"
        };

        // loadingExport1 简报 | loadingExport2 全部
        this['loadingExport' + (b ? 1 : 2)] = true;
        downFile('/api/pms/report/exportXlsx', param).then((data) => {
          this.loadingExport1 = false;
          this.loadingExport2 = false;

          if (!data) {
            this.$message.warning("文件下载失败");
            return;
          }

          let name = '我的绩效报表-' + (b ? '简报-' : '') + year.text + month.text;
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data]), name + '.xlsx');
          } else {
            let url = window.URL.createObjectURL(new Blob([data]));
            let link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.setAttribute('download', name + '.xlsx');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);    // 下载完成移除元素
            window.URL.revokeObjectURL(url);    // 释放掉 blob 对象
          }
        });
      },

            /* 显示评分参考 */
      showRefModal(record,param) {
        let indexDepartName = record.indexOrgName;
        let indexScorerName = '(' + record.scorerName + ')';
        this.modalInfo1 = {
          show: true,
          title: '部门「' + indexDepartName + indexScorerName + '」',
          date: this.yearList.val.value+"",
          departInfo: record,
          k:'gm',
          param:param
        }
          let par={
          id:"",
          scorerCode:record.scorerCode,
          indexOrgCode:record.indexOrgCode,
          year:this.yearList.val.value
        }
        // 通知弹窗组件更新数据
        setTimeout(() => { this.$refs.scoreRef.initData(1,true,par); }, 10);
      },

        click(record, index,param){
          let _this=this
          console.log(record,index,param)
          _this.showRefModal(record,param)
          },
        click1(record, index,param){
          let _this=this
          console.log(record,index,param)
          _this.showRefModal(record,param)
      }
    }
  }
</script>





<style lang="less" scoped>
  .menu-box {
    padding: 5px 10px 15px 10px;
    margin-bottom: 20px;
    border-bottom: 1px solid #e7e7e7;
  }

  .content-box {
    padding-left: 20px;

    .radio-box, .radio-org { margin-bottom: 10px; }

    .table-view, .table-detail {
      margin-bottom: 80px;

      .title {
        padding: 5px 5px 15px 5px;
        font-size: 16px;
        margin-bottom: 15px;
        border-bottom: 1px solid #e7e7e7;
        font-weight: bold;
      }
    }

    .score-ref {
      color: @primary-color;
      cursor: pointer;

      &:hover { text-decoration: underline; }
    }

    .radio-org, .radio-month {
      padding-left: 5px;
    }

    /deep/.ant-checkbox-wrapper {
      margin-left: 20px;
      font-size: 16px;
      font-weight: bold;
    }

    /deep/.ant-table th,
    /deep/.ant-table td { white-space: nowrap; padding: 10px; }
    /*/deep/.ant-table-tbody .ant-table-row td { padding: 10px; }*/

    /deep/.ant-table-tbody {
      .row-line-auto {
        background-color: #fef7eb;

        &:hover td {
          background-color: #fef7eb;
        }
      }

      .row-line-more {
        background-color: #fff0d8;
        font-weight: bold;

        &:hover td {
          background-color: #fff0d8;
        }
      }

      .row-line-deep {
        background-color: #ffffff;
        font-weight: bold;
        color: #14BA89;
        font-size: 16px;

        &:hover td {
          background-color: #ffffff;
        }
      }
    }

    /deep/.ant-table-content div.ant-table-placeholder {
      color: @primary-color;
      font-size: 16px;
      font-weight: bold;
      padding: 20px;
    }

    .pagination-box {
      margin-top: 20px;
      float: right;
    }

    .icon-chart {
      margin-left: 5px;
      color: @primary-color;
      cursor: pointer;
    }

    .view-switch-box {
      float: right;
      overflow: hidden;

      [class*="view-"] {
        float: left;
        padding: 1px 6px;
        margin-left: 5px;
        color: #cccccc;
        border-radius: 3px;
        border: 1px solid transparent;

        &:hover {
          color: #434343;
          background: #fafafa;
          border: 1px solid #e7e7e7;
          cursor: pointer;
        }
      }

      .checked-on, .checked-on:hover {
        background: @primary-color;
        color: #ffffff;
        cursor: default;
      }
    }
  }
</style>
